package demo;

import java.util.Arrays;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.*;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

// 字符串工具
public class StringTool extends Application {
	private VBox root = new VBox(40);
	private HBox hBox = new HBox(38);
	private TextArea ta = new TextArea("asdfghasdfasdfgh");
	private int i = 0;		// 查找功能中记录上次查找的结束下标
	
	public static void main(String[] args) {
		launch(args);
	}
	
	@Override
	public void start(Stage stage) {
		
		root.setPadding(new Insets(40));
		
		TextField tf = new TextField();
		Button find = new Button("查找");
		Button sort = new Button("排序");
		hBox.getChildren().addAll(tf, find, sort);
		
		ta = new TextArea("asdfghasdfghasdf");
		root.getChildren().addAll(hBox, ta);
		
		Scene scene = new Scene(root, 400, 300);
		stage.setScene(scene);
		stage.setTitle("StringTool");
		stage.show();
		
		// 事件
		find.setOnMouseClicked(e -> findString(tf, ta));
		sort.setOnMouseClicked(e -> sortString(ta));
	}
	
	// 字符串查找
	public void findString(TextField tf, TextArea ta) {
		String allValue = ta.getText();
		String findValue = tf.getText();
		String subValue = allValue.substring(i);
		if(subValue.contains(findValue)) {
			ta.requestFocus();	// 获得焦点
			int startIndex = subValue.indexOf(findValue) + i;
			int endIndex = startIndex + findValue.length();
			ta.selectRange(startIndex, endIndex);
			i = endIndex;	// 记录下标
		} else{
			i = 0;	// 循环选择
		}
	}
	
	// 字符串排序
	public void sortString(TextArea ta) {
		char[] temp = ta.getText().toCharArray();	// 用数组对文本排序
		Arrays.sort(temp);
		
		String sortedString = "";	// 把数组内容转成字符串
		for(char ch : temp) {
			sortedString += ch;
		}
		ta.setText(sortedString);
	}
}


